﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PubSubSubscriber;

namespace UbiMashGCFeatures
{
    public class UbiMashSubscriber
    {
        private Subscriber sub;
        private string msgReceived;
        private List<UbiMashListener> _listeners = new List<UbiMashListener>();
        private string _varname;
        //private UbiMashGCFeatures

        public void ConnectToUbiMash (string ipAdd, int portNo)
        {
            sub = new Subscriber(ipAdd, portNo);
            sub.messageChanged += UpdateMessage;
        }

        public void AddListener(UbiMashListener listener)
        {
            _listeners.Add(listener);
        }

        public void Subscribe(string varName)
        {
            _varname = varName;
            sub.Subscribe(varName);
        }

        public void Dispose()
        {
            //sub.Unsubscribe(_varname);
            //sub.Shutdown();
        }

        private void UpdateMessage(object sender, MessageChangedArgs args)
        {
            try
            {
                msgReceived = args.message;

                //Debug.WriteLine("message received: " + msgReceived);
                //Debug.Flush();

                if (!string.IsNullOrEmpty(msgReceived))
                {
                    string[] str = msgReceived.Trim().Split(',');

                    if ((str[1] != null && str[1] != ""))
                    {
                        string s = str[1].Trim();

                        //string format: "{0:1:2;3:4:5;}"
                        // remove {}
                        s = s.Substring(1);
                        s = s.Substring(0, (s.Length - 1));

                        foreach (UbiMashListener l in _listeners)
                        {
                            l.refresh(s);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                //Debug.WriteLine(e.Message);
                //Debug.WriteLine(e.StackTrace);
            }
            //Console.WriteLine(args.message);
        }
    }
}
